// pages/news/news.js
Page({
  data: {
    messages: [],
    inputValue: '',
    loading: false,
    scrollTop: 0,
    conversationId: '',
    currentAssistantMessageIndex: -1,
    receivedContent: '' // Track content that has been received
  },

  onLoad: function (options) {
    this.setData({
      messages: [
        {
          role: 'assistant',
          content: '您好！我是AI助手，可以为您提供最新的AI资讯和行业动态。请问您想了解什么内容？'
        }
      ]
    });
  },

  onInput: function (e) {
    this.setData({ inputValue: e.detail.value });
  },

  sendMessage: function () {
    const message = this.data.inputValue.trim();
    if (!message || this.data.loading) return;

    const newMessages = [...this.data.messages, { role: 'user', content: message }];
    this.setData({ 
      messages: newMessages, 
      inputValue: '', 
      loading: true,
      receivedContent: '' // Reset received content for new message
    });
    this.scrollToBottom();
    this.callCozeAPI(message);
  },

  callCozeAPI: function (message) {
    const that = this;
    const apiKey = '';
    const botId = '';
    const userId = '123';

    wx.request({
      url: 'https://api.coze.cn/v1/conversation/create',
      method: 'POST',
      header: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
      data: {},
      success: (createRes) => {
        if (createRes.data?.code === 0 && createRes.data?.data?.id) {
          const conversationId = createRes.data.data.id;
          that.setData({ conversationId });
          that.sendMessageWithConversation(conversationId, message, apiKey, botId, userId);
        } else {
          console.error('创建会话失败:', createRes);
          that.addAssistantMessage(`创建会话失败: ${createRes.data?.msg || '未知错误'}`);
          that.setData({ loading: false });
        }
      },
      fail: (err) => {
        console.error('创建会话请求失败:', err);
        that.addAssistantMessage('网络请求失败，请稍后重试。');
        that.setData({ loading: false });
      }
    });
  },

  sendMessageWithConversation: function (conversationId, message, apiKey, botId, userId) {
    const that = this;

    // Only add a new assistant message if one doesn't already exist
    let newMessages = [...this.data.messages];
    let currentAssistantMessageIndex = this.data.currentAssistantMessageIndex;
    
    // If no assistant message is currently being processed, add a new one
    if (currentAssistantMessageIndex === -1) {
      newMessages = [...newMessages, { role: 'assistant', content: '' }];
      currentAssistantMessageIndex = newMessages.length - 1;
      this.setData({ messages: newMessages, currentAssistantMessageIndex });
    }
    
    this.scrollToBottom();

    // 发起流式请求
    const requestTask = wx.request({
      url: `https://api.coze.cn/v3/chat?conversation_id=${conversationId}`,
      timeout: 60000,
      method: 'POST',
      header: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
      data: {
        bot_id: botId,
        user_id: userId,
        stream: true,
        auto_save_history: true,
        additional_messages: [{ role: "user", content: "AI日报", content_type: "text" }]
      },
      enableChunked: true,
      success: (chatRes) => console.log('对话API完整响应:', chatRes),
      fail: (err) => {
        console.error('对话API调用失败:', err);
        that.addAssistantMessage('网络请求失败，请稍后重试。');
        that.setData({ loading: false, currentAssistantMessageIndex: -1 });
      },
      complete: () => {
        that.setData({ loading: false, currentAssistantMessageIndex: -1 });
        that.scrollToBottom();
      }
    });

    // Process stream data
    requestTask.onChunkReceived((res) => {
      if (!res.data || !(res.data instanceof ArrayBuffer)) return;

      let dataStr;
      try {
        dataStr = new TextDecoder('utf-8').decode(res.data);
      } catch (e) {
        console.error('解码失败:', e);
        return;
      }

      const chunks = dataStr.split('\n\n');
      chunks.forEach(chunk => {
        if (!chunk.trim()) return;

        const lines = chunk.split('\n');
        let dataContent = null;

        lines.forEach(line => {
          const trimmedLine = line.trim();
          if (trimmedLine.startsWith('data:')) {
            dataContent = trimmedLine.slice(5).trim();
          }
        });

        if (!dataContent) return;

        if (dataContent === '[DONE]') {
          console.log('流式传输完成');
          return;
        }

        try {
          const data = JSON.parse(dataContent);
          
          // Process message content
          let contentToAdd = '';
          if (data.type === 'follow_up' && data.content) {
            contentToAdd = data.content + '\n';
          } else if (data.content) {
            try {
              const contentObj = JSON.parse(data.content);
              if (contentObj.content) {
                contentToAdd = contentObj.content;
              }
            } catch (e) {
              contentToAdd = data.content;
            }
          }
          
          // Only add content if it's not already in our received content
          if (contentToAdd && !that.data.receivedContent.includes(contentToAdd)) {
            that.updateAssistantMessage(contentToAdd);
            
            // Update received content tracking
            that.setData({
              receivedContent: that.data.receivedContent + contentToAdd
            });
          }
        } catch (error) {
          console.error('解析数据块出错:', error, '原始data内容:', dataContent);
        }
      });
    });
  },

  updateAssistantMessage: function (content) {
    const { messages, currentAssistantMessageIndex } = this.data;
    if (currentAssistantMessageIndex >= 0 && currentAssistantMessageIndex < messages.length) {
      const updatedMessages = [...messages];
      updatedMessages[currentAssistantMessageIndex].content += content;
      this.setData({ messages: updatedMessages }, () => this.scrollToBottom());
    }
  },

  addAssistantMessage: function (content) {
    const newMessages = [...this.data.messages, { role: 'assistant', content }];
    this.setData({ 
      messages: newMessages, 
      currentAssistantMessageIndex: -1,
      receivedContent: '' // Reset received content
    }, () => this.scrollToBottom());
  },

  scrollToBottom: function () {
    setTimeout(() => this.setData({ scrollTop: 999999 }), 100);
  }
});